<?php
// Copyright (c) 2009, wiztv-modules project
// All rights reserved.

// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following
// conditions are met:
// Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided with the distribution.
// Neither the name of the wiztv-modules project nor the names of its contributors may be used to endorse or promote
// products derived from this software without specific prior written permission.

// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
// BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
// EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

header('Content-type: application/xml');
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");

// XML Entity Mandatory Escape Characters
function xmlentities( $string )
    {
    return str_replace( array ( '&', '"', "'", '<', '>' ), array ( '&amp;' , '&quot;', '&apos;' , '&lt;' , '&gt;' ), $string );
    }

// user_id - the user's feed we are browsing
// album_id - the album we are browsing
// album_index - the album we are currently browsing
// photo_index - the photo we are currently viewing
$user_id = @$_GET["user_id"];
$album_id = @$_GET["album_id"];
$album_index = (int) @$_GET["album_index"];
$photo_index = (int) @$_GET["photo_index"];

$THUMBNAIL_SIZE = 144; // $THUMBNAIL_SIZE = 72;
$THUMBNAILS_PER_PAGE = 6;
$IMAGE_SIZE = 912; // 1280
$HEADER_HEIGHT = 80;
$HEADER_WIDTH = 860;
$BODY_X_OFFSET = 190;
$BODY_Y_OFFSET = 130;
$ENTRY_WIDTH = 450;
$ENTRY_HEIGHT = 170;
$ENTRY_X_SPACING = $ENTRY_WIDTH;
$ENTRY_Y_SPACING = $ENTRY_HEIGHT + 10;
$THUMBNAIL_PAD = round( ($ENTRY_HEIGHT - $THUMBNAIL_SIZE)/2 );
$THUMBNAIL_X_SPACE = $THUMBNAIL_PAD * 2 + $THUMBNAIL_SIZE + 5;
$TEXT_PAD = 13;
$TEXT_ENTRY_HEIGHT = $ENTRY_HEIGHT - $TEXT_PAD * 2;
$TEXT_ENTRY_WIDTH = $ENTRY_WIDTH - $THUMBNAIL_X_SPACE - $TEXT_PAD;

// always align pages on the same boundary - this is the index of the first photo on the page
$base_photo_index = floor($photo_index/$THUMBNAILS_PER_PAGE) * $THUMBNAILS_PER_PAGE;
$selected = $photo_index - $base_photo_index;

echo <<<EOS
<?xml version="1.0" encoding="ISO-8859-1" ?>
<subXML>
    <webPage name="PicasaWebAlbum"
             selectedobject="entry$selected"
             bgcolor="0x00000000"
             keepAspect="TRUE" fullcolor="TRUE" fullredraw="TRUE"
             >

        <drbList>
EOS;

// build feed URL
$request_start = $base_photo_index + 1;
$feedURL = "http://picasaweb.google.com/data/feed/api/user/$user_id/albumid/$album_id?thumbsize=" . $THUMBNAIL_SIZE . "c&start-index=$request_start&max-results=$THUMBNAILS_PER_PAGE";

// read feed into SimpleXML object
$sxml = @simplexml_load_file($feedURL);
if($sxml !== false)
{
    $counts = $sxml->children('http://a9.com/-/spec/opensearchrss/1.0/');
    $total = $counts->totalResults; // count of items in this album
    $start = $counts->startIndex; // one based offset
    $page_items = $counts->itemsPerPage; // count of possible number of items on this page
    $max_index = $page_items; // one based offset of last item within this page (from 1 to $THUMBNAILS_PER_PAGE)
    if ( ($total - $start + 1) < $max_index )
        $max_index = $total - $start + 1;

    $pages = ceil( $total/$THUMBNAILS_PER_PAGE );
    $page = floor( $photo_index/$THUMBNAILS_PER_PAGE ) + 1;

    $albumTitle = $sxml->title;

    echo <<<EOS
            <drb name="header" x="210" y="30" width="$HEADER_WIDTH" height="$HEADER_HEIGHT" hidesurface="FALSE">
                <drbElementList>
                    <drbElement name="PicasaLogo"
                        x="0" y="0"
                        width="50%"
                        hidesurface="FALSE"
                        imagealign="align_center"
                        file="images/Picasa-Logo-black.jpg"
                        />
                    <drbElement name="AlbumName"
                        skipX="5"
                        x="-1" y="30"
                        width="50%"
                        textalign="align_left"
                        bgcolor="0xFF000000" fgcolor="0xFFAAAAAA"
                        readonly="TRUE" hidesurface="FALSE" class="button" mline="FALSE"
                        text="Web Album: $albumTitle"
                        />
                    <drbElement name="AlbumPages"
                        x="same" y="60"
                        width="50%" height="15"
                        textalign="align_left"
                        bgcolor="0xFF000000" fgcolor="0xFFAAAAAA"
                        readonly="TRUE" hidesurface="FALSE" class="button" mline="FALSE"
                        fontfile="bitmaps/font_teletext_latin_primary.bmp"
                        text="Page $page of $pages"
                        />
                </drbElementList>
            </drb>
EOS;
    // iterate over entries in album
    // print each entry's title, size, dimensions, tags, and thumbnail image

    $index = 0; // index within this page 0 to one less than thumbnail count
    $row = 0;

    foreach ($sxml->entry as $entry)
        {
        $title = xmlentities($entry->title);
        $summary = xmlentities($entry->summary);

        $date_parts = explode("-", substr($entry->published,0,10));
        $timeval = mktime(0, 0, 0, $date_parts[1], $date_parts[2], $date_parts[0]);
        $date_string = date("M d, Y", $timeval);

        $gphoto = $entry->children('http://schemas.google.com/photos/2007');
        $size = $gphoto->size;
        $height = $gphoto->height;
        $width = $gphoto->width;

        $media = $entry->children('http://search.yahoo.com/mrss/');
        $thumbnail = $media->group->thumbnail;
        $thumb_url = $thumbnail->attributes()->{'url'};

        $x_pos = $BODY_X_OFFSET + $index%2 * $ENTRY_X_SPACING;
        $y_pos = $BODY_Y_OFFSET + $row * $ENTRY_Y_SPACING;

        $index_up = $index - 2;
        $index_down = $index + 2;
        $index_left = $index - 1;
        $index_right = $index + 1;

        $page_up_event = "";
        $key_up_attribute = "";
        if ( $index >= 2 )
            $key_up_attribute = 'keyup="entry' . $index_up . '"';
        else if ( $base_photo_index > 0 )
            {
            // top row of album thumbnails - jump to preceding page
            $prev_photo_index = $base_photo_index + $index - 2;
            $page_up_event = '<event name="OnUpKey" command="NAVIGATE_PAGE_COMMAND" value="./album.php?user_id=' . $user_id .
                             '&amp;album_id=' . $album_id .
                             '&amp;album_index=' . $album_index .
                             '&amp;photo_index=' . $prev_photo_index . '"/>';
            }

        $page_down_event = "";
        $key_down_attribute = "";
        if ( $index < ($max_index - 2) )
            $key_down_attribute = 'keydown="entry' . $index_down . '"';
        else if ( $max_index < ($total - $start + 1) )
            {
            // bottom row of album thumbnails, and not last thumbnail - jump to next page
            $next_photo_index = $base_photo_index + $index + 2;
            if ( ($next_photo_index + 1) > $total )
                $next_photo_index--; // only one thumbnail on the next page
            $page_down_event = '<event name="OnDownKey" command="NAVIGATE_PAGE_COMMAND" value="./album.php?user_id=' . $user_id .
                               '&amp;album_id=' . $album_id .
                               '&amp;album_index=' . $album_index .
                               '&amp;photo_index=' . $next_photo_index . '"/>';
            }

        $key_right_attribute = "";
        if ( ($index%2 == 0) && ($index != ($max_index - 1)) )
            $key_right_attribute = 'keyright="entry' . $index_right . '"';

        $key_left_attribute = "";
        if ( $index%2 != 0 )
            {
            $key_left_attribute = 'keyleft="entry' . $index_left . '"';
            $row++;
            }

        $current_index = $base_photo_index + $index;

        echo <<<EOS
            <drb name="entry$index" x="$x_pos" y="$y_pos" width="$ENTRY_WIDTH" height="$ENTRY_HEIGHT"
                 $key_down_attribute $key_up_attribute $key_left_attribute $key_right_attribute
                 hidesurface="FALSE" class="button" focusstyle="outline" bgcolor="0xFF000000" fgcolor="0xFFAAAAAA">
                <drbElementList>
                    <drbElement name="Thumb$index"
                        x="$THUMBNAIL_PAD" y="$THUMBNAIL_PAD" width="$THUMBNAIL_SIZE" height="$THUMBNAIL_SIZE"
                        readonly="TRUE" hidesurface="TRUE" class="button" file="$thumb_url" />
                    <drbElement name="Title$index"
                        x="$THUMBNAIL_X_SPACE" y="$TEXT_PAD" width="$TEXT_ENTRY_WIDTH" height="$TEXT_ENTRY_HEIGHT"
                        readonly="TRUE" hidesurface="FALSE" class="button" mline="TRUE"
                        bgcolor="0xFF000000" fgcolor="0xFFAAAAAA" focusfontcolor="0xFFFFFFFF"
                        text="$title" textalign="align_left" verticalalign="align_middle"
                        />
                    <drbElement name="Info$index"
                        x="$THUMBNAIL_X_SPACE" y="142" width="$TEXT_ENTRY_WIDTH" height="15"
                        readonly="TRUE" hidesurface="FALSE" class="button" mline="FALSE"
                        fontfile="bitmaps/font_teletext_latin_primary.bmp"
                        bgcolor="0xFF000000" fgcolor="0xFFAAAAAA" focusfontcolor="0xFFFFFFFF"
                        text="$date_string" textalign="align_left" verticalalign="align_top"
                        />
                </drbElementList>
                <eventList>
                    <event name="OnSelect" command="VFD_TEXT_COMMAND" value="$title"/>
                    <event name="OnOkKey" command="NAVIGATE_PAGE_COMMAND"
                           value="./photo.php?user_id=$user_id&amp;album_id=$album_id&amp;album_index=$album_index&amp;photo_index=$current_index"/>
                    $page_up_event $page_down_event
                </eventList>
            </drb>
EOS;
        $index++;
        if ( $index == $page_items )
            break;
    }
    echo <<<EOS
        </drbList>

        <eventList>
            <event name="OnWizTvKey" command="NAVIGATE_PAGE_COMMAND" value="/WizTV/"/>
            <event name="OnReturnKey" command="NAVIGATE_PAGE_COMMAND"
                   value="user.php?user_id=$user_id&amp;album_id=$album_id&amp;album_index=$album_index"/>
        </eventList>
    </webPage>
    </subXML>
EOS;
}
else
{
    echo <<<EOS
    <drb name="error"
    x="250" y="260" width="700" height="150"
    marginx="10"
    class="normalText" hidesurface="FALSE"
    text="Can not load album for '$user_id'.
Please ensure that the Picasa user name is correct."
    mline="TRUE">
    </drb>
</drbList>

<eventList>
    <event name="OnWizTvKey" command="NAVIGATE_PAGE_COMMAND" value="/WizTV/"/>
    <event name="OnAnyKey" command="NAVIGATE_PAGE_COMMAND" value="./"/>
</eventList>
</webPage>
</subXML>
EOS;

}

